package cc.rengu.redp.common.render.core;

import cc.rengu.redp.common.render.dict.DictRenderer;
import cc.rengu.redp.common.render.core.Renderer;
import cc.rengu.redp.common.render.core.RenderService;
import cc.rengu.redp.common.utils.SpringContextUtil;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RenderServiceImpl implements RenderService {

    /**
     * key = 待渲染字段， value = 渲染器
     */
    private static Map<String, Renderer> renderers = new ConcurrentHashMap<>();

    @Override
    public void addRender(Class<? extends Renderer> clz){
        Renderer renderer = SpringContextUtil.getBean(clz);
        //此处加载渲染器
        renderers.put(renderer.getRenderFieldName(), renderer);
    }

    @Override
    public Boolean isRenderField(String field){
        for (Renderer renderer : renderers.values()) {
            if (renderer.isRenderField(field)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public String render(String field, String key, String defaultValue) {
        Renderer renderer = renderers.get(field);
        String value;
        // 没有配置渲染器的字段优先使用数据字典进行渲染
        if (renderer == null){
            renderer = renderers.get(DictRenderer.SYSTEM_DICT);
        }

        value = renderer.getFieldRender(field, key);

        if (value == null){
            return defaultValue;
        }

        return value;
    }
}
